package com.qfmy.webapp.service.impl.wallpaper;


import com.qfmy.model.entity.wallpaper.EmojiGroup;
import com.qfmy.model.vo.wallpaper.EmojiGroupVo;
import com.qfmy.webapp.mapper.wallpaper.EmojiGroupMapper;
import com.qfmy.webapp.service.wallpaper.EmojiGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.service.impl.wallpaper
 * @date 2025/11/26
 * @description 表情分组
 */
@Service
@SuppressWarnings("all")
public class EmojiGroupServiceImpl implements EmojiGroupService {

    /**
     * 注入mapper
     */
    @Autowired
    private EmojiGroupMapper emojiGroupMapper;

    /**
     * 注入redisTemplate
     */
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取表情分组名称
     * @param categoryId
     * @param num
     * @param size
     * @return
     */
    @Override
    public List<EmojiGroupVo> getEmojiGroupNameByType(Integer categoryId, Integer num, Integer size) {
        //校验参数
        if (num < 1 || size < 1) {
            num = 1;
            size = 6;
        }
        //计算分页
        int startIndex = (num - 1) * size;
        //创建缓存key
        String key = "wallpaper:emojiGroup:name:" + categoryId + ":" + num + ":" + size;
        if (redisTemplate.hasKey(key)) {
            return (List<EmojiGroupVo>) redisTemplate.opsForValue().get(key);
        }
        List<EmojiGroup> emojiGroups = emojiGroupMapper.getEmojiGroupNameByType(categoryId, startIndex, size);
        //校验
        if(emojiGroups != null)
        {
            //创建list
            List<EmojiGroupVo> list = new ArrayList<>();
           //转换数据
            emojiGroups.forEach(emojiGroup -> {
                EmojiGroupVo emojiGroupVo = new EmojiGroupVo(emojiGroup.getId(), emojiGroup.getName(), emojiGroup.getEmojis());
                list.add(emojiGroupVo);
            });
            //缓存
            redisTemplate.opsForValue().set(key, list, 24, TimeUnit.HOURS);
            return list;
        }else{
            //缓存
            redisTemplate.opsForValue().set(key, Collections.emptyList(), 1, TimeUnit.HOURS);
            return Collections.emptyList();
        }
    }
}
